/*
 * @Descripttion:
 * @version:
 * @Author: lily
 * @Date: 2021-04-07 17:34:23
 * @LastEditors: lily
 * @LastEditTime: 2021-04-07 17:43:59
 */
/**
 * @param {number} n
 * @return {number}
 */

//  思路：
//  https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof/solution/mian-shi-ti-43-1n-zheng-shu-zhong-1-chu-xian-de-2/

//  复杂度：O(logn) O(1)


var countDigitOne = function (n) {
    let digit = 1, res = 0
    let high = Math.floor(n / 10), curr = n % 10, low = 0
    while (high !== 0 || curr !== 0) {
        if (curr === 0) {
            res += high * digit
        } else if (curr === 1) {
            res += high * digit + low + 1
        } else {
            res += (high + 1) * digit
        }
        low += curr * digit
        curr = high % 10
        high = Math.floor(high / 10)
        digit *= 10
    }
    return res
};

console.log(countDigitOne(32104));